<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button v-permission="'add-role'" size="mini" type="primary" @click="showDialog=true">添加角色 </el-button>
      </div>

      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column align="center" width="200" label="角色">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template v-slot="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else>  {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>

          </template>

        </el-table-column>

        <el-table-column align="center" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template #default="{row}">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="confirmEdit(row)">确定</el-button>
              <el-button size="mini" type="denger" @click="cancelEdit(row)">取消</el-button>
            </template>
            <template v-else>
              <el-button v-permission="'assign-role'" size="mini" type="text" @click="showPers(row.id)">分配权限</el-button>

              <el-button v-permission="'edit-role'" size="mini" type="text" @click="roleEdit(row)">编辑</el-button>

              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" v-permission="'del-role'" size="mini" type="text" style="margin-left:10px">删除</el-button>
              </el-popconfirm>

            </template>

          </template>

        </el-table-column>

      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>

    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
      <!-- 表单内容 -->
      <el-form ref="roleRef" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>

        <el-form-item label="启用">
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>

        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOK">确定</el-button>

              <el-button size="mini" @click="btnCancel">取消</el-button>

            </el-col>

          </el-row>

        </el-form-item>

      </el-form></el-dialog>
    <el-dialog width="500px" title="分配权限" :visible.sync="showPersDialog" @close="cancel">
      <el-tree ref="perRef" :data="pers" :props="{label:'name'}" node-key="id" :default-checked-keys="permIds" default-expand-all show-checkbox check-strictly />
      <el-button type="primary" size="mini" @click="btnPermissionOK">确定</el-button>

      <el-button size="mini" @click="cancel">取消</el-button>

    </el-dialog>
  </div>

</template>
<script>
import { getPermissionAPI } from '@/api/permission'
import { assignPermAPI, delRoleAPI, editRoleAPI, getRoleDetailAPI, getRoleListAPI } from '@/api/role'
import { addRoleAPI } from '@/api/role'
import { transObjToTree } from '@/utils'
import { Message } from 'element-ui'
export default {
  data() {
    return {
      currentId: '',
      permIds: [],
      showPersDialog: false,
      pers: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: 0
      },
      showDialog: false,
      list: [{
        name: '',
        state: 0,
        description: ''

      }],
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }

    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async btnPermissionOK() {
      await assignPermAPI({ id: this.currentId, permIds: this.$refs.perRef.getCheckedKeys() })
      this.permIds = this.$refs.perRef.getCheckedKeys()
      Message.success('分配角色权限成功')
      this.cancel()
    },
    cancel() {
      this.showPersDialog = false
    },
    async showPers(id) {
      this.currentId = id
      this.showPersDialog = true
      this.pers = transObjToTree(await getPermissionAPI(), 0)
      const { permIds } = await getRoleDetailAPI(id)
      this.permIds = permIds
    },
    async getRoleList() {
      const { rows, total } = await getRoleListAPI(this.pageParams)
      this.list = rows
      this.pageParams.total = total
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    async changePage(newpage) {
      this.pageParams.page = newpage
      await this.getRoleList()
    },
    async btnOK() {
      await this.$refs.roleRef.validate()
      await addRoleAPI(this.roleForm)
      this.$message.success('新增角色成功')
      this.getRoleList()
      this.btnCancel()
    },
    btnCancel() {
      this.$refs.roleRef.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    },
    roleEdit(row) {
      row.isEdit = true
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async cancelEdit(row) {
      row.isEdit = false
    },
    async confirmEdit(row) {
      if (!row.editRow.name.trim() || !row.editRow.description.trim()) {
        Message.warning('角色名和描述不能为空')
        return
      }
      await editRoleAPI({ id: row.id, ...row.editRow })
      Object.assign(
        row, {
          isEdit: false,
          ...row.editRow
        }
      )
    },
    async confirmDel(id) {
      console.log(id)

      await delRoleAPI(id)
      if (this.list.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page -= 1
      }
      this.getRoleList()
      Message.success('删除成功')
    }
  }

}
</script>
<style scoped>
  .role-operate {
  padding: 10px;
}
</style>
